<template>
  <div class="app-container">
    <div class="bgWhite radius8 plr20 pt30 pb30">
		<div class="mb20">
		  <span class="fb fs16">线下渠道商机分配规则</span>		  
		</div>
		<div class="mb20">
			<el-form class="flex col-top row-between" :model="queryParams" ref="queryForm" :inline="true"
			  v-show="showSearch">
			  <el-form-item label="分配规则:" prop="logisticsCompany" label-width="80px"  style="margin-bottom: 0;">
			    <el-radio-group v-model="radioValue" @change="handleRadioChange">
			      <el-radio class="bus-radio-button-selected-bg-color" label="" value="">全部展示
			      </el-radio>
			      <el-radio class="bus-radio-button-selected-bg-color" v-for="item in bus_opportuity_rules_type_2"
			        :label="item.value" :value="item.value">{{ item.label }}
			      </el-radio>
			    </el-radio-group>
			  </el-form-item>
			</el-form>
		</div>	
      <div class="ml5">
		  <el-table v-loading="loading" :data="handleRadioChangeTableData"
		  :header-row-style="{
		    background: '#FAFAFA',
		    color: '#0C1019',
		    height: '54px',
		  }" :cell-style="{ height: '54px' }"
		  >
		    <el-table-column label="主键" align="center" prop="id" v-if="false" />
		  
		    <el-table-column label="部门名称" align="center" prop="deptName" />
		    <el-table-column label="主管人员" align="center" prop="leader" />
		    <el-table-column label="规则数量" align="center" prop="executionContent">
		      <template #default="scope">
		        {{ countRules(scope.row.executionContent) }}
		      </template>
		    </el-table-column>
		    <el-table-column label="商机分配规则" align="center" prop="executionType">
		      <template v-slot="scope">
		        <dict-tag :options="bus_opportuity_rules_type_2" :value="scope.row.executionType" />
		      </template>
		    </el-table-column>
		  
		    <el-table-column label="更新时间" align="center" prop="updateTime">
		      <template #default="scope">
		        <p v-if="scope.row.updateTime">{{ scope.row.updateTime }}</p>
		        <p v-else>{{ scope.row.createTime }}</p>
		      </template>
		    </el-table-column>
		  
		    <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
		      <template #default="scope">
		        <el-button link class="linkBtnColor" type="primary"  @click="handleUpdate(scope.row)"
				v-hasPermi="['offline:edit']"
				>修改分配规则
		        </el-button>
		      </template>
		    </el-table-column>
		  </el-table>
	  </div>
    <div class="bgWhite radius8 p20 plr20 pt30 pb20">
      <div class="mb20">
        <span class="fb fs16">线下渠道商机分配规则</span>
      </div>
      <div class="mb20">
        <el-form class="flex col-top row-between" :model="queryParams" ref="queryForm" :inline="true"
                 v-show="showSearch">
          <el-form-item label="分配规则" prop="logisticsCompany" style="margin-bottom: 0;">
            <el-radio-group v-model="radioValue" @change="handleRadioChange">
              <el-radio class="bus-radio-button-selected-bg-color" label="" value="">全部展示
              </el-radio>
              <el-radio class="bus-radio-button-selected-bg-color" v-for="item in bus_opportuity_rules_type_2"
                        :label="item.value" :value="item.value">{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="handleRadioChangeTableData">
        <el-table-column label="主键" align="center" prop="id" v-if="false"/>

        <el-table-column label="部门名称" align="center" prop="deptName"/>
        <el-table-column label="主管人员" align="center" prop="leader"/>
        <el-table-column label="规则数量" align="center" prop="executionContent">
          <template #default="scope">
            {{ countRules(scope.row.executionContent) }}
          </template>
        </el-table-column>
        <el-table-column label="商机分配规则" align="center" prop="executionType">
          <template v-slot="scope">
            <dict-tag :options="bus_opportuity_rules_type_2" :value="scope.row.executionType"/>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template #default="scope">
            <p v-if="scope.row.updateTime">{{ scope.row.updateTime }}</p>
            <p v-else>{{ scope.row.createTime }}</p>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link class="linkBtnColor" type="primary" @click="handleUpdate(scope.row)">修改分配规则
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>

    <!-- 添加或修改商机规则对话框 -->
    <el-dialog :title="title" center v-model="open" width="540px" append-to-body :key="opportunity_offline_dialog">
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="选择部门" prop="ids">
          <el-select :disabled="true" v-model="selectDeptValue" placeholder="Select" style="width: 800px" clearable
                     multiple>
            <template #label="{ label, value }">
              <span>{{ label }}: </span>
              <span style="font-weight: bold">{{ value }}</span>
            </template>
            <el-option v-for="item in selectDept" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="分配规则" prop="executionType">
          <el-radio-group v-model="formData.executionType">
            <el-radio class="bus-radio-button-selected-bg-color" v-for="item in bus_opportuity_rules_type_2"
                      :label="item.value" :value="item.value">{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right mt30">
        <el-button class="cancelSubBtn" @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" class="mainSubBtn">确 定</el-button>
      </div>
    </el-dialog>
	</div>
  </div>
</template>

<script setup name="OpportunityOfflineRulesSetup">
import {listAllByOffline, addOfflineRules} from "@/api/business/rules_opportunity";

const {proxy} = getCurrentInstance();
const {bus_opportuity_rules_type_2, bus_channel} =
    proxy.useDict("bus_opportuity_rules_type_2", "bus_channel");

//默认单选参数
const radioValue = ref("");
const radioAddValue = ref("");

//部门默认下拉
var selectDept = [];
const selectDeptValue = ref([]);

//折叠
const isExpandAll = ref(true);
//刷新表单
const refreshTable = ref(true);
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 商机规则表格数据
const rulesList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  level: 3,
  channel: "1002"
});
// 表单参数
const formData = ref({
  ids: [],
  executionType: "",
});

// 内联表 表单校验规则
const customValidator = (rule, value, callback) => {
  value.forEach(e => {
    if (!e.crop && !e.target && !e.otherLabel)
      return callback(new Error("每条规则内容,至少需要选择1项"));
  });
  callback();
};

// 表单校验
const rules = ref({
  ids: [{required: true, message: "选择部门不能为空", trigger: "blur"}],
  executionType: [
    {required: true, message: "分配规则不能为空", trigger: "blur"},
  ]
});

// 计算规则数量
function countRules(rules) {
  if (!rules) return 0;
  return rules.length;
}

/** 查询商机规则列表 */
function getList() {
  loading.value = true;
  rulesList.value = null
  listAllByOffline(queryParams.value).then((response) => {
    rulesList.value = proxy.handleTree(response.data, "deptId");
    total.value = response.total;
    loading.value = false;
  });
}

function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  proxy.resetForm("form");
  formData.value = {
    ids: [],
    executionType: "",
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

// 列表行数据过滤
const handleRadioChangeTableData = computed(() => {
  if (radioValue.value === "") {
    // 如果过滤条件为空，返回所有数据
    return rulesList.value;
  } else {
    // 否则，返回过滤后的数据
    // 在这里添加你的过滤逻辑
    // 例如，根据 name 属性进行过滤
    return rulesList.value.filter(
        (item) => item.executionType === radioValue.value
    );
  }
});

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 行 修改分配规则 初始化数据 */
function buildUpdateData(row) {
  formData.value.executionType = row.executionType
  selectDept = [];
  selectDeptValue.value = [];

  selectDept.push({
    label: row.deptName,
    value: row.deptId,
  });
  selectDeptValue.value.push(row.deptId);
}

/** 行 修改分配规则 */
function handleUpdate(row) {
  getList();
  reset();
  buildUpdateData(row);

  open.value = true;
  title.value = "修改分配规则";
}

/** 提交按钮 */
function submitForm() {
  formData.value.ids = selectDeptValue.value;
  console.log("submitForm===", formData.value);
  proxy.$refs["form"].validate((valid) => {
    if (valid) {
      addOfflineRules(formData.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

getList();
watch(() => bus_channel.value, arr => {
  queryParams.value.channel = arr[1].value
  console.log("ol_public", queryParams.value.channel)
})
</script>
